// components/goods-detail-gb-started-item/goods-detail-gb-started-item.js 商品详情已经开团cell
let common_js = require("../../utils/common.js");

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    icon: {
      type: String,
      value: ''
    },
    nikeName: {
      type: String,
      value: ''
    },
    number: {
      type: Number,
      value: ''
    },
    expire: {
      type: Number,
      value: '',
      observer(newVal, oldVal, changedPath) {
        if (newVal) {
          //初始化倒计时
          this.initTimer(newVal);
        }
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    timerObj: { //倒计时
      timer: null,
      isEnd: false,
      endTime: '',
      item: null
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onPd: function() {
      this.triggerEvent('pd', null, {});
    },

    //初始化计时器
    initTimer: function(expire) {
      if (expire == 0) {
        let tmpTimerObj = this.data.timerObj;
        tmpTimerObj.hou = "00";
        tmpTimerObj.min = "00";
        tmpTimerObj.sec = "00";
        this.setData({
          timerObj: tmpTimerObj,
        });
        return;
      }
      let tmpTimerObj = this.data.timerObj;
      if (tmpTimerObj.timer) {
        clearTimeout(tmpTimerObj.timer);
      }
      tmpTimerObj.endTime = new Date().getTime() + expire * 1000;
      this.setData({
        timerObj: tmpTimerObj,
      });
      //start
      this.countTimer();
    },

    // 计时器**********
    countTimer() { //倒计时函数
      // 获取当前时间，同时得到活动结束时间数组
      let newTime = new Date().getTime();
      let tmpTimerObj = this.data.timerObj;
      let endTime = tmpTimerObj.endTime;
      let time = (endTime - newTime) / 1000;
      // 如果活动未结束，对时间进行处理
      let hmsObj = common_js.getHrMinSecBySecond(time);
      tmpTimerObj.item = hmsObj.item;
      tmpTimerObj.isEnd = hmsObj.isEnd;
      //1s调用一次
      let that = this;
      let timerItem = setTimeout(function() {
        that.countTimer()
      }, 1000);
      //定时清除
      clearTimeout(this.data.timerObj.timer);
      if (tmpTimerObj.isEnd) {
        clearTimeout(timerItem);
        return;
      } else {
        tmpTimerObj.timer = timerItem;
      }
      // 渲染，然后每隔一秒执行一次倒计时函数
      this.setData({
        timerObj: tmpTimerObj
      })
    }
    // 计时器**********
  },

  //组件生命周期函数-在组件实例被从页面节点树移除时执行
  detached: function() {
    if (this.data.timerObj.timer) {
      clearTimeout(this.data.timerObj.timer);
    }
  }
})